import fingerprintjs2 from "fingerprintjs2"

const fingerName = "finger"

/**
 * @description 获取localStorage
 * @param {String} key Storage名称
 * @return string
 */
export const localGet = (key: string) => {
	const value = window.localStorage.getItem(key)
	try {
		return JSON.parse(window.localStorage.getItem(key) as string)
	} catch (error) {
		return value
	}
}

/**
 * @description 存储localStorage
 * @param {String} key Storage名称
 * @param {Any} value Storage值
 * @return void
 */
export const localSet = (key: string, value: any) => {
	window.localStorage.setItem(key, JSON.stringify(value))
}

export default {
	load() {
		return new Promise(resolve => {
			fingerprintjs2.get(function (components: { value: any }[]) {
				const values = components.map(function (component) {
					return component.value
				})
				const murmur = fingerprintjs2.x64hash128(values.join(""), 31)
				localSet(fingerName, murmur)
				resolve(murmur)
			})
		})
	},
	async get(): Promise<string> {
		let finger = localGet(fingerName)
		if (!finger) {
			finger = await this.load()
		}

		return finger
	}
}
